package com.example.electricbicycle.controller;

import com.example.electricbicycle.po.VehicleStock;
import utils.DBUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/StockQueryServlet")
public class StockQueryServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        List<VehicleStock> stockList = new ArrayList<>();
        int page = 1;
        int pageSize = 5;
        int totalPages = 0;
        int totalRecords = 0;

        try (Connection conn = DBUtils.getConnection()) {
            // 分页参数处理
            String pageParam = request.getParameter("page");
            if (pageParam != null && !pageParam.isEmpty()) {
                try {
                    page = Integer.parseInt(pageParam);
                } catch (NumberFormatException e) {
                    // 无效页码时使用默认值
                    page = 1;
                }
            }

            // 获取总记录数
            String countSql = "SELECT COUNT(*) AS total FROM vehicle_stock";
            try (PreparedStatement countPstmt = conn.prepareStatement(countSql);
                 ResultSet countRs = countPstmt.executeQuery()) {
                if (countRs.next()) {
                    totalRecords = countRs.getInt("total");
                }
            }

            // 计算总页数
            totalPages = (int) Math.ceil((double) totalRecords / pageSize);

            // 确保当前页码在有效范围内
            if (page < 1) {
                page = 1;
            } else if (page > totalPages && totalPages > 0) {
                page = totalPages;
            }

            // 查询当前页数据
            String dataSql = "SELECT id, v_id, quantity, last_update " +
                    "FROM vehicle_stock ORDER BY last_update DESC " +
                    "LIMIT ? OFFSET ?";
            try (PreparedStatement dataPstmt = conn.prepareStatement(dataSql)) {
                dataPstmt.setInt(1, pageSize);
                dataPstmt.setInt(2, (page - 1) * pageSize);

                try (ResultSet rs = dataPstmt.executeQuery()) {
                    while (rs.next()) {
                        // 注意字段顺序与DAO构造函数参数顺序完全匹配
                        stockList.add(new VehicleStock(
                                rs.getInt("id"),
                                rs.getInt("v_id"),       // 车辆ID
                                rs.getInt("quantity"),   // 库存数量
                                rs.getTimestamp("last_update")  // 最后更新时间
                        ));
                    }
                }
            }

            // 设置请求属性
            request.setAttribute("stockList", stockList);
            request.setAttribute("currentPage", page);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("querySuccess", true);

        } catch (SQLException e) {
            // 数据库错误处理
            request.setAttribute("errorMessage", "数据库操作失败: " + e.getMessage());
            request.getRequestDispatcher("/WEB-INF/error/db_error.jsp").forward(request, response);
            return;
        } catch (Exception e) {
            // 通用错误处理
            request.setAttribute("errorMessage", "系统错误: " + e.getMessage());
            request.getRequestDispatcher("/WEB-INF/error/500.jsp").forward(request, response);
            return;
        }

        // 转发到安全路径
        request.getRequestDispatcher("/warehouse/stock.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }
}